<template>
  <view>
    <view v-if="!payOrderShow">
      <!-- 头部导航栏 -->
      <view class="top-navigate bg-yellow" style="padding: 53px 10px 130px 10px;">
        <view class="content cuIcon-back text-xl top-navigate-title" @click="goBack"></view>
        <view class="text-xl top-navigate-title">万能帮</view>
      </view>
      <!-- 需求信息 -->
      <view class="needs-message">
        <form>
          <!-- 多行输入框 -->
          <view class="text-df" style="margin-left: 30rpx;font-weight: 700;">帮助内容:</view>
          <view class="cu-form-group">
            <textarea maxlength="-1" v-model="orderInfo.helpInfo.content" placeholder="请填写帮助信息,例如:拼车,技术帮,租借东西,海底捞..."
              class="needs-textarea"></textarea>
          </view>
          <!-- 补充物品图片 -->
          <view class="flex text-sm" style="margin: 15px 30rpx;">
            <view class="cuIcon-pic text-orange margin-right">
              补充图片
            </view>
            <view class="text-gray ">
              请勿将重要隐私暴露
            </view>
          </view>
          <!-- 图片显示区域 -->
          <form>
            <view class="cu-form-group">
              <view class="grid col-4 grid-square flex-sub">
                <view class="bg-img" v-for="(item,index) in tmpImgList" :key="index" @tap="ViewImage" :data-url="item">
                  <image :src="item" mode="aspectFill" style="position: absolute;left:0"></image>
                  <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
                    <text class='cuIcon-close'></text>
                  </view>
                </view>
                <view class="solids" @tap="ChooseImage" v-if="tmpImgList.length<4">
                  <text class='cuIcon-cameraadd'></text>
                </view>
              </view>
            </view>
          </form>
          <!-- 提示 -->
          <view class="cu-form-group tips">
            <button class="cu-btn round bg-blue shadow lg" style="margin: 15px 0;width: 90%;"
              @click="placeOrder">立即发布</button>
          </view>

        </form>
      </view>

    </view>
    <!-- <pay-order v-if="payOrderShow" :orderId="orderId" :price="price"></pay-order> -->
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import getCurrentDateTime from '../../utils/currentTime.js'
  const db = uniCloud.database();
  export default {
    data() {
      return {
        //订单信息
        orderInfo: {
          type: '万能帮',
          userId: '',
          helpInfo: {
            content: '',
            imgList: [],
          },
          state: '待接单',
          publishTime: ''
        },
        //服务协议checkbox
        checkbox: false,
        //当前下单的订单ID
        orderId: '',
        //临时商品图
        tmpImgList: [],
        payOrderShow: false
      };
    },
    onLoad() {
      this.orderInfo.userId = this.userinfo._id
    },
    methods: {
      goBack() {
        uni.navigateBack(-1)
      },
      //点击上传商品图片事件
      ChooseImage() {
        const that = this;
        uni.showActionSheet({
          itemList: ['从相册选择', '拍照'], // 显示的操作列表
          success: function(res) {
            if (!res.cancel) {
              if (res.tapIndex === 0) {
                // 用户选择了从相册选择
                uni.chooseImage({
                  count: 4, //默认9
                  sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                  sourceType: ['album'], //从相册选择
                  success: (res) => {
                    console.log(res);
                    if (that.tmpImgList.length != 0) {
                      that.tmpImgList = that.tmpImgList.concat(res.tempFilePaths)
                    } else {
                      that.tmpImgList = res.tempFilePaths
                    }
                  }
                });
              } else if (res.tapIndex === 1) {
                // 用户选择了拍照
                uni.chooseImage({
                  count: 1,
                  sourceType: ['camera'], // 拍照
                  success: function(res) {
                    // 用户拍照后的处理逻辑
                    console.log(res.tempFilePaths);
                    that.tmpImgList = that.tmpImgList.concat(res.tempFilePaths)
                  }
                });
              }
            }
          }
        });
      },
      //上传图片操作
      async uploadImg() {
        for (var i = 0; i < this.tmpImgList.length; i++) {
          let filePath = this.tmpImgList[i]
          //进行上传图片操作
          const result = await uniCloud.uploadFile({
            filePath: filePath,
            cloudPath: 'all-purpose-gang' + '-' + i + '.png',
          });
          this.orderInfo.helpInfo.imgList.push(result.fileID)
        }
      },
      ViewImage(e) {
        uni.previewImage({
          urls: this.tmpImgList,
          current: e.currentTarget.dataset.url
        });
      },
      DelImg(e) {
        uni.showModal({
          title: this.userinfo.user_name,
          content: '确定要删除这张物品图片吗？',
          cancelText: '取消',
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              this.tmpImgList.splice(e.currentTarget.dataset.index, 1)
            }
          }
        })
      },
      //下单 添加订单事件回调
      async placeOrder() {
        // if (!this.checkbox) return uni.$showMsg('请先同意服务协议')
        //满足下单要求 将订单信息图片上传
        if (this.tmpImgList) await this.uploadImg();
        this.orderInfo.publishTime=getCurrentDateTime()
        console.log(this.orderInfo);
        const {
          result: res
        } = await db.collection("my_order").add(this.orderInfo)
        //根据订单id 携带到子组件 支付订单
        this.orderId = res.id
        console.log('订单id：', this.orderId);
        if (res.id) {
          //this.payOrderShow = true
          uni.redirectTo({
            url: '/pages/index/index'
          })
          return uni.$showMsg('发布成功！');
        }
      },
      //服务协议点击更改勾选事件
      CheckboxChange() {
        this.checkbox = !this.checkbox
      },
    },
    computed: {
      ...mapState('m_user', ['userinfo']),
    }
  }
</script>

<style lang="scss">
  .top-navigate {
    display: flex;
    justify-content: left;
    align-items: center;

    .top-navigate-title {
      margin: 0 5px;
      font-weight: bold;
    }

    .top-navigate-address {
      margin: 0 5px;
    }
  }

  .needs-message {
    position: relative;
    padding: 5px;
    background-color: white;
    top: -120px;
    width: 95%;
    border-radius: 10px;
    margin: 0 auto;

    .needs-textarea {
      height: 150px;
      padding: 5px;
      border-radius: 10px;
      border: 1px solid black;
    }

    .btn-needs-address {
      display: flex;
      align-items: center;
      margin: 0;

    }

    .tips {
      display: flex;
      flex-direction: column;
      align-items: center;

      .margin-top {
        padding-top: 5px;
      }
    }
  }

  .service-agreement {
    position: relative;
    margin: 0 auto;
    width: 95%;
    top: -90px;
    display: flex;
    align-items: center;

    .service-txt {
      margin-left: 10px;
      font-size: 14px;
    }
  }
</style>